package se.webbzon.oschi01.nbt;

import java.io.DataOutputStream;
import java.io.IOException;

import se.webbzon.oschi01.singleton.Singleton;
import se.webbzon.oschi01.utils.Writer;

public class NBTDataOutputStreamWriter implements Singleton, Writer<Tag<?>,DataOutputStream> {
	
	private NBTDataOutputStreamWriter() {};
	
	public <T> void genericWrite(Tag<T> root, DataOutputStream dos) throws IOException {
		TagFactory<T> factory = root.getFactory();
		dos.writeByte(factory.getId());
		if (!factory.isNameless()) {
			String tagName = root.toString();
			byte[] data = tagName.getBytes("utf-8");
			dos.writeShort(data.length);
			dos.write(data);
		}
		factory.writeTag(root, dos);
	}

	@Override public void write(Tag<?> data, DataOutputStream destination) throws IOException {
		genericWrite(data,destination);
	}

}
